package com.kujawnode.config.handler;

import com.kujawnode.constant.Constants;
import com.kujawnode.model.TUser;
import com.kujawnode.result.R;
import com.kujawnode.service.RedisService;
import com.kujawnode.utils.JSONUtils;
import com.kujawnode.utils.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @version 1.0
 * @Author kujaw
 * @Date 2025/7/11 21:01
 * @注释
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onLogoutSuccess(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication
    ) throws IOException, ServletException {
        //退出成功，执行改方法，在该方法中返回json给前端
        TUser tUser = (TUser) authentication.getPrincipal();

        //删除redis中的jwt
        redisService.removeValue(Constants.REDIS_JWT_KEY +tUser.getId());

        R result = R.OK(200,"退出成功");

        String resultJSON = JSONUtils.toJSON(result);

        ResponseUtils.write(response,resultJSON);
    }
}
